package demo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-09-17
 * Time: 20:06
 */
public class Solution {
    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, Solution.ListNode next) { this.val = val; this.next = next; }
    }
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null && list2 == null) {
            return null;
        }
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        ListNode newHead = new ListNode(-1);
        ListNode cur = newHead;

        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                cur.next = list1;
                cur = cur.next;
                list1 = list1.next;
            }else {
                cur.next = list2;
                cur = cur.next;
                list2 = list2.next;
            }
        }

        while (list1 != null) {
            cur.next = list1;
            cur = cur.next;
            list1 = list1.next;
        }

        while (list2 != null) {
            cur.next = list2;
            cur = cur.next;
            list2 = list2.next;
        }

        return newHead.next;
    }
}
